"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const mobx_miniprogram_bindings_1 = require("mobx-miniprogram-bindings");
const index_1 = require("../../../store/index");
const order_1 = require("../../../services/order");
const toast_1 = require("../../../utils/toast");
const tabBar_1 = require("../../../utils/tabBar");
const DINER_STATUS_META = {
    pending: { label: "待处理", desc: "厨师未接收" },
    accepted: { label: "已接收", desc: "厨师已确认，稍等开做" },
    rejected: { label: "已拒绝", desc: "" },
    cooking: { label: "制作中", desc: "美食正在出炉" },
    completed: { label: "已完成", desc: "快来评价这顿美味" },
};
const CHEF_TABS = [
    { key: "pending", title: "待处理" },
    { key: "accepted", title: "已接收" },
    { key: "cooking", title: "制作中" },
    { key: "completed", title: "已完成" },
    { key: "rejected", title: "已拒绝" },
];
Page({
    data: {
        isChef: index_1.globalStore.isChef,
        loading: true,
        currentOrders: [],
        historyOrders: [],
        chefOrders: [],
        chefTabs: CHEF_TABS,
        chefActiveTab: "pending",
        actionLoading: false,
        showReviewPanel: false,
        reviewOrderId: "",
        reviewRating: 5,
        reviewComment: "",
        reviewSubmitting: false,
        ratingOptions: [1, 2, 3, 4, 5],
        showRejectPanel: false,
        rejectOrderId: "",
        rejectReason: "",
        lastPromptedReviewId: "",
    },
    storeBindings: null,
    onLoad() {
        this.storeBindings = (0, mobx_miniprogram_bindings_1.createStoreBindings)(this, {
            store: index_1.globalStore,
            fields: ["isChef"],
            actions: ["setOrders", "updateOrderSnapshot", "setActiveOrder"],
        });
    },
    onUnload() {
        var _a, _b;
        (_b = (_a = this.storeBindings) === null || _a === void 0 ? void 0 : _a.destroyStoreBindings) === null || _b === void 0 ? void 0 : _b.call(_a);
    },
    onShow() {
        return __awaiter(this, void 0, void 0, function* () {
            yield index_1.globalStore.initAppData();
            const isChef = index_1.globalStore.isChef;
            this.setData({ isChef });
            (0, tabBar_1.applyTabBar)(isChef ? "chef" : index_1.globalStore.isDiner ? "diner" : "guest");
            yield this.loadOrders();
        });
    },
    onPullDownRefresh() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.loadOrders();
            wx.stopPullDownRefresh();
        });
    },
    loadOrders(statusKey) {
        return __awaiter(this, void 0, void 0, function* () {
            this.setData({ loading: true });
            try {
                if (this.data.isChef) {
                    const activeKey = statusKey || this.data.chefActiveTab;
                    const res = yield (0, order_1.fetchOrders)({ role: "chef", status: activeKey });
                    index_1.globalStore.setOrders(res.orders);
                    const enriched = res.orders.map((order) => this.enrichOrder(order));
                    this.setData({ chefOrders: enriched, chefActiveTab: activeKey });
                }
                else {
                    const res = yield (0, order_1.fetchOrders)({ role: "diner" });
                    index_1.globalStore.setOrders(res.orders);
                    const enriched = res.orders.map((order) => this.enrichOrder(order));
                    const current = enriched.filter((order) => ["pending", "accepted", "cooking"].includes(order.status));
                    const history = enriched.filter((order) => ["completed", "rejected"].includes(order.status));
                    this.setData({ currentOrders: current, historyOrders: history });
                    this.autoPopupReview(enriched);
                }
            }
            catch (error) {
                console.error("加载订单失败", error);
                wx.showToast({ title: "加载失败", icon: "none" });
            }
            finally {
                this.setData({ loading: false });
            }
        });
    },
    enrichOrder(order) {
        const funTotal = order.items.reduce((sum, item) => sum + item.funValue * item.quantity, 0);
        const statusMeta = DINER_STATUS_META[order.status] ||
            { label: order.status, desc: "" };
        return Object.assign(Object.assign({}, order), { funTotal, statusLabel: statusMeta.label, statusDesc: statusMeta.desc, createdText: this.formatTime(order.createdAt), updatedText: this.resolveUpdateTime(order) });
    },
    resolveUpdateTime(order) {
        if (order.status === "completed") {
            return this.formatTime(order.finishedAt || order.closedAt);
        }
        if (order.status === "cooking") {
            return this.formatTime(order.startedAt);
        }
        if (order.status === "accepted") {
            return this.formatTime(order.acceptedAt);
        }
        if (order.status === "rejected") {
            return this.formatTime(order.rejectedAt || order.closedAt);
        }
        return "";
    },
    formatTime(value) {
        if (!value)
            return "";
        return value.replace("T", " ").slice(0, 16);
    },
    autoPopupReview(orderList) {
        if (this.data.isChef)
            return;
        const target = orderList.find((order) => order.status === "completed" && !order.review);
        if (!target)
            return;
        if (this.data.lastPromptedReviewId === target._id)
            return;
        this.setData({
            showReviewPanel: true,
            reviewOrderId: target._id,
            reviewRating: 5,
            reviewComment: "",
            lastPromptedReviewId: target._id,
        });
    },
    handleChefTabChange(event) {
        if (!this.data.isChef)
            return;
        if (this.data.actionLoading)
            return;
        const { key } = event.currentTarget.dataset;
        if (!key || key === this.data.chefActiveTab)
            return;
        this.loadOrders(key);
    },
    handleChefAccept(event) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.data.isChef || this.data.actionLoading)
                return;
            const { id } = event.currentTarget.dataset;
            if (!id)
                return;
            this.setData({ actionLoading: true });
            try {
                const res = yield (0, order_1.acceptOrder)({ orderId: id });
                index_1.globalStore.updateOrderSnapshot(res.order);
                (0, toast_1.toast)("已接单");
                yield this.loadOrders();
            }
            catch (error) {
                console.error("接单失败", error);
                (0, toast_1.toast)(error.message || "操作失败");
            }
            finally {
                this.setData({ actionLoading: false });
            }
        });
    },
    handleOpenRejectPanel(event) {
        if (!this.data.isChef || this.data.actionLoading)
            return;
        const { id } = event.currentTarget.dataset;
        if (!id)
            return;
        this.setData({
            showRejectPanel: true,
            rejectOrderId: id,
            rejectReason: "",
        });
    },
    handleRejectReasonInput(event) {
        const value = (event.detail.value || "").slice(0, 60);
        this.setData({ rejectReason: value });
    },
    handleCloseRejectPanel() {
        this.setData({
            showRejectPanel: false,
            rejectOrderId: "",
            rejectReason: "",
        });
    },
    handleSubmitReject() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.data.isChef || this.data.actionLoading)
                return;
            if (!this.data.rejectOrderId)
                return;
            const reason = (this.data.rejectReason || "").trim();
            if (!reason) {
                (0, toast_1.toast)("请填写拒绝原因");
                return;
            }
            this.setData({ actionLoading: true });
            try {
                const res = yield (0, order_1.rejectOrder)({
                    orderId: this.data.rejectOrderId,
                    reason,
                });
                index_1.globalStore.updateOrderSnapshot(res.order);
                (0, toast_1.toast)("已拒绝");
                this.handleCloseRejectPanel();
                yield this.loadOrders();
            }
            catch (error) {
                console.error("拒绝失败", error);
                (0, toast_1.toast)(error.message || "操作失败");
            }
            finally {
                this.setData({ actionLoading: false });
            }
        });
    },
    handleChefStart(event) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.data.isChef || this.data.actionLoading)
                return;
            const { id } = event.currentTarget.dataset;
            if (!id)
                return;
            this.setData({ actionLoading: true });
            try {
                const res = yield (0, order_1.startCooking)(id);
                index_1.globalStore.updateOrderSnapshot(res.order);
                (0, toast_1.toast)("开始制作啦");
                yield this.loadOrders();
            }
            catch (error) {
                console.error("开始制作失败", error);
                (0, toast_1.toast)(error.message || "操作失败");
            }
            finally {
                this.setData({ actionLoading: false });
            }
        });
    },
    handleChefFinish(event) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.data.isChef || this.data.actionLoading)
                return;
            const { id } = event.currentTarget.dataset;
            if (!id)
                return;
            this.setData({ actionLoading: true });
            try {
                const res = yield (0, order_1.finishCooking)(id);
                index_1.globalStore.updateOrderSnapshot(res.order);
                (0, toast_1.toast)("已完成");
                yield this.loadOrders();
            }
            catch (error) {
                console.error("完成失败", error);
                (0, toast_1.toast)(error.message || "操作失败");
            }
            finally {
                this.setData({ actionLoading: false });
            }
        });
    },
    handleViewDetail(event) {
        const { id } = event.currentTarget.dataset;
        if (!id)
            return;
        index_1.globalStore.setActiveOrder(id);
        wx.navigateTo({ url: `/pages/order/detail/index?id=${id}` });
    },
    handleOpenReview(event) {
        if (this.data.isChef)
            return;
        const { id } = event.currentTarget.dataset;
        if (!id)
            return;
        this.setData({
            showReviewPanel: true,
            reviewOrderId: id,
            reviewRating: 5,
            reviewComment: "",
        });
    },
    handleRatingChange(event) {
        const { value } = event.currentTarget.dataset;
        const rating = Math.min(5, Math.max(1, Number(value || 0)));
        this.setData({ reviewRating: rating });
    },
    handleReviewInput(event) {
        const value = (event.detail.value || "").slice(0, 120);
        this.setData({ reviewComment: value });
    },
    handleCloseReview() {
        this.setData({
            showReviewPanel: false,
            reviewOrderId: "",
            reviewComment: "",
        });
    },
    handleSubmitReview() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.data.reviewOrderId || this.data.reviewSubmitting)
                return;
            this.setData({ reviewSubmitting: true });
            try {
                const res = yield (0, order_1.submitReview)({
                    orderId: this.data.reviewOrderId,
                    rating: this.data.reviewRating,
                    comment: this.data.reviewComment,
                });
                index_1.globalStore.updateOrderSnapshot(res.order);
                (0, toast_1.toast)("感谢评价");
                this.handleCloseReview();
                yield this.loadOrders();
            }
            catch (error) {
                console.error("评价失败", error);
                (0, toast_1.toast)(error.message || "评价失败");
            }
            finally {
                this.setData({ reviewSubmitting: false });
            }
        });
    },
});
